package com.dingxin.ship_together_api.common.utils;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.dingxin.ship_together_api.config.exception.CustomException;
import com.dingxin.ship_together_api.entity.RouteSpu;
import com.dingxin.ship_together_api.entity.SysUser;
import com.dingxin.ship_together_api.entity.constant.RoleConstant;
import com.dingxin.ship_together_api.entity.enums.ExceptionEnum;
import com.dingxin.ship_together_api.entity.vo.PageQueryVo;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: ctj
 * Date: 2022-09-15
 * Time: 11:00
 */
@Component
public class SaUtils {
    /**
     * 判断此角色是否为当前用户角色之一
     * @param roleName
     * @return
     */
    public boolean currentUserContains(String roleName){
        List<String> role_list = (List<String>)StpUtil.getSession().get(SaSession.ROLE_LIST);
        return role_list.contains(roleName);
    }


    /**
     * 根据用户角色生成查询条件：当前端传参指定角色时使用指定的，未指定时按用户角色权限范围从大到小取一个
     * 当用户角色为管理员时展示所有，非管理员时展示自己的
     * @param queryWrapper
     * @param pageQueryVo
     * @param <T>
     * @return
     */
    public <T> QueryWrapper<T> generateQueryWrapper(QueryWrapper<T> queryWrapper, PageQueryVo pageQueryVo) {
        // 准备数据
        queryWrapper.eq(RouteSpu.COL_DELETED,false);
        SysUser user = (SysUser)StpUtil.getSession().get(RoleConstant.USER);
        ArrayList<String> roleList = (ArrayList<String>)StpUtil.getSession().get(SaSession.ROLE_LIST);
        // 逻辑处理
        if (StringUtils.isBlank(pageQueryVo.getCurrUserRole())) {
            if (roleList.contains(RoleConstant.ADMIN)) {
                return queryWrapper;
            }else{
                return queryWrapper.eq(RouteSpu.COL_CREATE_BY,user.getId());
            }
        }else {
            if (!roleList.contains(pageQueryVo.getCurrUserRole())) {
                throw new CustomException(ExceptionEnum.ROLE_NOT_FOUND);
            }
            switch (pageQueryVo.getCurrUserRole()) {
                case RoleConstant.ADMIN:
                    break;
                case RoleConstant.SHIPMASTER:
                case RoleConstant.USER:
                    queryWrapper.eq(RouteSpu.COL_CREATE_BY,user.getId());
                    break;
            }
        }
        return queryWrapper;
    }
}
